package com.alipay.rebate.shop.helper;

import com.alipay.rebate.shop.constants.SmsGroupSendConstant;
import com.alipay.rebate.shop.dao.mapper.BrowseProductMapper;
import com.alipay.rebate.shop.dao.mapper.OrdersMapper;
import com.alipay.rebate.shop.dao.mapper.SmsGroupSendMapper;
import com.alipay.rebate.shop.dao.mapper.UserMapper;
import com.alipay.rebate.shop.model.SmsGroupSend;
import com.alipay.rebate.shop.utils.AliUtil;
import com.aliyuncs.exceptions.ClientException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class SmsMessageSender {

  private Logger logger = LoggerFactory.getLogger(SmsMessageSender.class);
  @Resource
  private UserMapper userMapper;
  @Resource
  private SmsGroupSendMapper smsGroupSendMapper;
  @Resource
  private BrowseProductMapper browseProductMapper;
  @Resource
  private OrdersMapper ordersMapper;

  private Gson gson = new GsonBuilder().create();

  public void sendSms(SmsGroupSend smsGroupSend){

    updateStatusToSending(smsGroupSend);

    switch (smsGroupSend.getSendObj()){
      // 手机号发送
      case SmsGroupSendConstant
          .PHONE_OBJ:
        phoneObjSend(smsGroupSend);
        break;
      // 所有用户
      case SmsGroupSendConstant
          .ALL_USER_OBJ:
        allObjSend(smsGroupSend);
        break;
      // 活跃用户
      case SmsGroupSendConstant
          .ACTIVE_USER_OBJ:
        activeObjSend(smsGroupSend);
        break;
      // 沉睡用户
      case SmsGroupSendConstant
          .SLEEP_USER_OBJ:
        sleepObjSend(smsGroupSend);
        break;
      // 新用户
      case SmsGroupSendConstant
          .NEW_USER_OBJ:
        newObjSend(smsGroupSend);
        break;
      // 最近下单用户
      case SmsGroupSendConstant
          .BUY_USER_OBJ:
        buyObjSend(smsGroupSend);
        break;
    }
  }

  // 按照手机号码发送
  public void phoneObjSend(SmsGroupSend smsGroupSend){
    String phoneNum = smsGroupSend.getPhoneNum();
    try {
      List<String> phone = Arrays.asList(phoneNum.split(","));
      // 发送短信
      AliUtil.sendSmsBatch(gson.toJson(phone),phone.size(),smsGroupSend.getContent());
      // 将发送状态设置成完成状态
      updateStatusToComplete(smsGroupSend);
    } catch (ClientException e) {
      logger.error(""+e);
    }
  }

  // 发送给所有人
  // TODO 暂时以全量获取来发送,代码分页
  public void allObjSend(SmsGroupSend smsGroupSend){

    List<String> allPhone = userMapper.selectAllPhone();
    logger.debug("allPhone size is : {}",allPhone.size());
    logger.debug("allPhone is : {}",allPhone);
    doSend(allPhone,smsGroupSend);

  }

  // 发送给活跃用户
  public void activeObjSend(SmsGroupSend smsGroupSend){

    List<String> allPhone = browseProductMapper.selectActiveUserPhone(smsGroupSend.getConditionDay());
    logger.debug("allPhone size is : {}",allPhone.size());
    logger.debug("allPhone is : {}",allPhone);
    doSend(allPhone,smsGroupSend);

  }

  // 发送给沉睡用户
  public void sleepObjSend(SmsGroupSend smsGroupSend){

    List<String> allPhone = browseProductMapper.selectSleepUserPhone(smsGroupSend.getConditionDay());
    logger.debug("allPhone size is : {}",allPhone.size());
    logger.debug("allPhone is : {}",allPhone);
    doSend(allPhone,smsGroupSend);

  }

  // 发送给新注册用户
  public void newObjSend(SmsGroupSend smsGroupSend){

    List<String> allPhone = userMapper.selectNewRegisUserPhone(smsGroupSend.getConditionDay());
    logger.debug("allPhone size is : {}",allPhone.size());
    logger.debug("allPhone is : {}",allPhone);
    doSend(allPhone,smsGroupSend);

  }


  // 发送给新注册用户
  public void buyObjSend(SmsGroupSend smsGroupSend){

    List<String> allPhone = ordersMapper.selectRecentBuyUserPhone(smsGroupSend.getConditionDay());
    logger.debug("allPhone size is : {}",allPhone.size());
    logger.debug("allPhone is : {}",allPhone);
    doSend(allPhone,smsGroupSend);

  }

  private void doSend(List<String> allPhone,SmsGroupSend smsGroupSend){
    try {
      // 如果手机号数目小于100，直接发送
      if(allPhone.size() <=100){
        String phoneJson = gson.toJson(allPhone);
        AliUtil.sendSmsBatch(phoneJson,allPhone.size(),smsGroupSend.getContent());
      }else {
        doSendByPage(allPhone,smsGroupSend.getContent());
      }
      updateStatusToComplete(smsGroupSend);
    } catch (ClientException e) {
      logger.error(""+e);
    }
  }

  private void doSendByPage(List<String> allPhone,String content){
    int count = allPhone.size();
    int pageSize = 100;
    int temp = count % pageSize > 0 ? 1 : 0;
    int maxPage = count/pageSize + temp;
    for(int i=1; i<=maxPage; i++){
      try {
        if (i < maxPage) {
          List<String> tempPhone = allPhone.subList((i - 1) * pageSize, i * pageSize);
          String phoneJson = gson.toJson(tempPhone);
          AliUtil.sendSmsBatch(phoneJson, 100,content);
        }
        if (i == maxPage) {
          List<String> tempPhone = allPhone.subList((i - 1) * pageSize, count);
          String phoneJson = gson.toJson(tempPhone);
          AliUtil.sendSmsBatch(phoneJson, count % pageSize,content);
        }
      }catch (Exception ex){
        logger.error(""+ex);
      }
    }
  }

  private void updateStatusToComplete(SmsGroupSend smsGroupSend){
    // 将发送状态设置成完成状态
    SmsGroupSend nSgs = new SmsGroupSend();
    nSgs.setId(smsGroupSend.getId());
    nSgs.setStatus(SmsGroupSendConstant.COMPLETE_STATUS);
    smsGroupSendMapper.updateByPrimaryKeySelective(nSgs);
  }

  private void updateStatusToSending(SmsGroupSend smsGroupSend){
    // 将发送状态设置成发送种
    SmsGroupSend nSgs = new SmsGroupSend();
    nSgs.setId(smsGroupSend.getId());
    nSgs.setStatus(SmsGroupSendConstant.SENDING_STATUS);
    smsGroupSendMapper.updateByPrimaryKeySelective(nSgs);
  }
}
